package org.person.gift.listener.trans;

import com.alibaba.fastjson.JSONObject;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.person.gift.constants.OrderConstant;
import org.person.gift.dto.PlaceOrderDTO;
import org.person.gift.service.IOrderGiftService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

@Component
@RocketMQTransactionListener(txProducerGroup = OrderConstant.PLACE_ORDER_TX_PRODUCER_GROUP)
public class PlaceOrderLocalTransactionListener implements RocketMQLocalTransactionListener {

    @Autowired
    private IOrderGiftService orderGiftService;

    /**
     * 执行本地事务
     * @param msg
     * @param arg
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        // 1 接收消息队列的消息
        byte[] payload = (byte[])msg.getPayload();
        String str = new String(payload);
        PlaceOrderDTO dto = JSONObject.parseObject(str, PlaceOrderDTO.class);

        // 2 执行本地事务
        try {
            orderGiftService.placeOrderExecuteLocalTransaction(dto);
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RocketMQLocalTransactionState.ROLLBACK;
    }

    /**
     * 回查本地事务
     * @param msg
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        // 1 接收消息队列的消息
        byte[] payload = (byte[])msg.getPayload();
        String str = new String(payload);
        PlaceOrderDTO dto = JSONObject.parseObject(str, PlaceOrderDTO.class);

        // 2 执行本地事务
        try {
            Boolean result = orderGiftService.placeOrderCheckLocalTransaction(dto);
            if(result){
                return RocketMQLocalTransactionState.COMMIT;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RocketMQLocalTransactionState.ROLLBACK;
    }
}
